package com.example.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.example.common.constant.AuthServerConstant;
import com.example.common.utils.R;
import com.example.gulimall.auth.feign.MemberFeignService;
import com.example.gulimall.auth.vo.UserLoginVo;
import com.example.gulimall.auth.vo.UserRegistVo;
import com.example.gulimall.auth.feign.ThirdPartFeignService;
import exception.BizCodeEnum;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import com.example.common.vo.*;
import java.util.stream.Collectors;

import static com.example.common.constant.AuthServerConstant.LOGIN_USER;

@Controller
public class LoginController {

    @Autowired
    ThirdPartFeignService thirdPartFeignService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    MemberFeignService memberFeignService;
    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone){
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PEEFIX + phone);
        if (!StringUtils.isEmpty(redisCode)){
            long l = Long.parseLong(redisCode.split("_")[1]);
            //当前系统时间是以毫秒为单位，我们存的是60秒，因此乘以1000
            if (System.currentTimeMillis()-l<60000){
                //60 秒内，不能再发
                return R.error(BizCodeEnum.VAILD_SMS_CODE.getCode(), BizCodeEnum.VAILD_SMS_CODE.getMsg());
            }

        }

        //  TODO 1接口防刷
        // 2 验证码再次校验 redis 存key-phone value-code sms:code:15526101205-<45678
        String code = UUID.randomUUID().toString().substring(0, 5)+"_"+System.currentTimeMillis();
        //redis 缓存验证码，防止同一个手机号在60秒内再次发送验证码

        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PEEFIX+phone,code,10, TimeUnit.MINUTES);

        thirdPartFeignService.sendCode(phone,code);
        return R.ok("验证码发送成功");
    }

    /**
     * TODO 重定向携带数据，原理是用session,将数据放在sessionz中，
     * 只要跳到下一个页面取出这个数据以后，session里面的数据就会删掉
     * TODO 1 分布式下session问题
     * 开启Valid JSR303 数据校验，BindResult 校验的结果
     * RedirectAttributes 模拟重定向携带数据
     * @param vo
     * @param result
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult result, RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            // 校验出错，转发到注册
            //这里会有一个问题，因为一个字段有多个注解验证，如果一个字段同时多个注解不满足
            //就会引发多个错误，导致封装到map有多个相同的key,引发异常
//             Map<String, String> errors = result.getFieldErrors().stream()
//                     .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            Map<String, String> errors = new HashMap<>();
            for (FieldError fieldError : result.getFieldErrors()) {
                //如果有多个错误，只存储一个，否则map键值重复报错
                //不能指定数据校验顺序问题
                if (!errors.containsKey(fieldError.getField())) {
                    errors.put(fieldError.getField(), fieldError.getDefaultMessage());
                }

            }
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.mall.com/reg.html";
        }
        // 真正的注册
        // 1 校验验证码
        String code = vo.getCode();
        String s = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PEEFIX + vo.getPhone());
        if (!StringUtils.isEmpty(s)) {
            //截串获取验证码
            String s1 = s.split("_")[0];
            if (code.equals(s1)) {
                //验证码通过
                // 删除验证码,令牌机制
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PEEFIX + vo.getPhone());
                R regist = memberFeignService.regist(vo);
                if (regist.getCode() == 0) {
                    //成功
                    //注册成功，回到登录页
                    return "redirect:http://auth.mall.com/";
                } else {
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", regist.getData("msg", new TypeReference<String>() {
                    }));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.mall.com/reg.html";
                }

            } else {
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", errors);
            }

        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.mall.com/reg.html";
        }

        return "redirect:http://auth.mall.com";
    }

    /**
     * 如果用户已经是登录状态，在访问登录页面直接跳转到首页
     * @param session
     * @return
     */

    @GetMapping(value = {"/login.html","/"})
    public String loginPage(HttpSession session) {

        //从session先取出来用户的信息，判断用户是否已经登录过了
        Object attribute = session.getAttribute(LOGIN_USER);
        //如果用户没登录那就跳转到登录页面
        if (attribute == null) {
            return "login";
        } else {
            return "redirect:http://mall.com";
        }

    }

    /**
     * 账号密码登录
     * @param loginVo
     * @param attributes
     * @param session
     * @return
     */
    @PostMapping("/login")
    public String login(UserLoginVo loginVo,RedirectAttributes attributes, HttpSession session){
        R login = memberFeignService.login(loginVo);
        if (login.getCode() == 0) {
            MemberRespVo data = login.getData("data", new TypeReference<MemberRespVo>() {});
            session.setAttribute(LOGIN_USER,data);
            return "redirect:http://mall.com";
        } else {
            Map<String,String> errors = new HashMap<>();
            errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.mall.com/login.html";
        }
    }
}
